import { Tools } from '@/utils'

// api
import { fetchMenuNav } from '@/api'

const initState = {
  subjectId: '1'
}

export default {
  namespaced: true,
  state: {
    ...initState,
    menuListAll: [],
    menuList: [],
    menuTree: [],
    mainWait: false,
    initState () {
      return initState
    }
  },
  actions: {
    getMenuListAll ({ commit }, params) {
      return new Promise(resolve => {
        fetchMenuNav(params).then(res => {
          if (res.code === 200) {
            const info = res.data
            info.sort((o1, o2) => {
              if (o1.parentId === o2.parentId) {
                return o1.orderNum - o2.orderNum
              } else {
                return o1.parentId - o2.parentId
              }
            })
            commit('setMenuList', info)
            resolve(info)
            return
          }
          commit('setMenuList', [])
          resolve([])
          console.log(res)
        }).catch(err => {
          commit('setMenuList', [])
          resolve([])
          console.log(err)
        })
      })
    }
  },
  mutations: {
    setMenuList (state, info) {
      const { listToTree } = Tools
      const infoSub = info.filter(menu => menu.type < 2)
      const infoTree = listToTree(infoSub, { idName: 'menuId', pidName: 'parentId' })
      state.menuListAll = info
      state.menuList = infoSub
      state.menuTree = infoTree
    },
    setSubjectId (state, info) {
      state.subjectId = info
    },
    setMainWait (state, info) {
      state.mainWait = info
    }
  }
}
